// 主界面
;
define(function(require, exports, module) {
	'use strict';
	var util = require("util");
	var base = require("base");
	var leftMenu = require("../leftMenu/leftMenu");
	var topMenu = require("../topMenu/topMenu");
	var router = require("../hash/pageRouter");
	var dialog = require("dialog");
	var validate = require("validate");
	var databind = require("databind");
	var tools = require("tools");
	var js_platform_main = require("./platform_main.js");
	var css_supervisionNotice = require("./supervisionNotice.css");
	var html_financingDetail_recieveNotice = require("../financing/financingDetail_recieveNotice.html");
	var html_confirmReceive = require("./html_confirmReceive.html");
	var html_confirmSupervise = require("./html_confirmSupervise.html");
	var ws;
	var toClientId;
	var pageIndex = 1,
		pageSize = 20,
		totalPageCount = 1,
		totalRecordCount = 0; //分页初始化
	var imgSrc;
	var rd;
	var checkeds = [];
	var financeId;
	var financeNumber;
	var loanNoticeId;
	var tallyingId;
	var tallyingState;
	var productType;
	var left;
	var init = function(page) {
		pageIndex = 1;
		left = page.params.left || base.getUrlParam("left");
		financeId = page.params.financeId || base.getUrlParam("financeId");
		productType = page.params.productType || base.getUrlParam("productType");
		financeNumber = page.params.financeNumber || base.getUrlParam("financeNumber");
		tallyingId = page.params.tallyingId || base.getUrlParam("tallyingId");
		var js_platform_main = require("./platform_main.js");
		$(".left").removeClass("none");
		leftMenu.init(6);
		$(".table-section").removeClass("none");
		$(".footer").removeClass("none");
		$("#main").css("background", "#ffffff");
		$("#leftMenu7").find(".leftMenu-item").removeClass("leftMenu-active");
		$("#leftMenu7 .leftMenu li:first-child").addClass("leftMenu-open");
		$("#leftMenu7").find(".leftMenu-item").eq(left).addClass("leftMenu-active");
		initEvent();
		inquireWaitLoanNoticeBulkstockInventoryList();
		js_platform_main.init(0);
		router.init();
	};
	var initEvent = function() {
		
		//若未登录，则返回登陆页面
		if (base.getData("sid") == null || base.getData("sid") == "" || base.getData("sid") == undefined) {
			top.location.href = "../login/login.html";
		}

		//点击首页
		$(".platform_main").unbind("click").click(function() {
			top.location.href = "../main/platform_main.html";
		});

		//收货确认和监管确认
		$(".supervisionNotice_list").unbind("click").click(function() {
			router.route("main/supervisionNotice_list.html?financeId="+financeId);
		});

		//button_unusual点击异常信息
		$(".tallying_base").on("click", ".button_unusual", function() {
			dialog.showDialog($("#unusualReportTask-dialog"), function() {});
			$(".uploadFileSoundRecorde").css("display", "none");
			$(".uploadFileAbnormalFile").css("display", "none");
			inquireTallyingDetailUnusual(tallyingId);
			$("#sureabnormal").remove();
			databind.disableInput($("#unusualReportTask-dialog"));
		});

		//扣货申请
		$("#supervisionNotice .detainedApplication").unbind("click").click(function() {
			router.route("detainedApplication/accountDetainedApplication1.html?financeId=" + financeId + "&tallyingId=" + tallyingId + "&left=" + left, true);
		});

		//点击理货 详情
		$("#supervisionNotice").on("click", ".tallyingListDetail", function() {
			var inventoryId = [];
			var $this = $(this).parents("tr.tr_style");
			inventoryId.push($this.attr("inventoryId"));
			if ($("#supervisionNotice .ws").is(":checked")) {
				if (rd == null) {
					getRandomCode(function(){
						passData(rd, inventoryId);
//						window.open("../pc/pc.html?randomCode=" + rd);
						window.open("../crossingScreen/pc/index.html?randomCode=" + rd);
					});
				} else {
					passData(rd, inventoryId);
				}
				
			} else {
				router.route("main/tallyDetail.html?inventoryId=" + inventoryId + "&tallyingId=" + tallyingId + "&type=readOnly&financeId=" + financeId + "&left=" + left, true);
			}
		});

		//点击重新理货
		$("#supervisionNotice").on("click", ".repeatRecieve", function() {
			if (productType == 3 || productType == 5 || productType == 6) {
				if (checkeds.length > 0) {
					$("#popdialog").html(html_financingDetail_recieveNotice);
					$("#recieveNotice_dialog input[name=recieveNoticeId]").remove();
					$("#recieveNotice_dialog .dialogTitle").html("重新理货");
					$("#recieveNotice_dialog").find(".financing_field-lab3:last").remove();
					$("#recieveNotice_dialog textarea[name=noticeRemark]").removeClass("field-input").css("width", "553px");
					$("#recieveNotice_dialog .dialogContent").attr("action", "createRepeatRecieveNotice");
					$("#recieveNotice_dialog input[name=financeId]").val(financeId);
					$("#recieveNotice_dialog	 a[name=financeNumber]").html(financeNumber);
					
					$("#supervisionCompanyName").parent().remove();
					
					$.each(checkeds, function() {
						var str = '<input name="inventoryId" value="' + this + '" type="hidden"/>';
						$("#recieveNotice_dialog .dialogContent").append(str);
					});
					
					dialog.showDialog($("#recieveNotice_dialog"));
					
					$("#recieveNotice_dialog .dialogHandlerBtn").unbind("click").click(function(){
						databind.submitDom($("#recieveNotice_dialog .dialogContent"), function(){
							base.alert(1, "打回成功！");
							dialog.hideDialog($("#recieveNotice_dialog"));
							inquireWaitLoanNoticeBulkstockInventoryList();
						});
					});
				} else {
					base.alert(3, "请选择要打回的入库单！");
				}
			} else {
				if (checkeds.length > 0) {
					$("#popdialog").html(html_financingDetail_recieveNotice);
					$("#recieveNotice_dialog input[name=recieveNoticeId]").remove();
					$("#recieveNotice_dialog .dialogTitle").html("重新理货");
					$("#recieveNotice_dialog").find(".financing_field-lab3:last").remove();
					$("#recieveNotice_dialog textarea[name=noticeRemark]").removeClass("field-input").css("width", "553px");
					$("#recieveNotice_dialog .dialogContent").attr("action", "createRepeatRecieveNotice");
					$("#recieveNotice_dialog input[name=financeId]").val(financeId);
					
					$.each(checkeds, function() {
						var str = '<input name="inventoryId" value="' + this + '" type="hidden"/>';
						$("#recieveNotice_dialog .dialogContent").append(str);
					});
					loadLogisticsCompanyPageList("supervisionCompanyName", "supervisionTpl");
					
					$("#recieveNotice_dialog").on("change", "#supervisionCompanyName", function(){
						$("input[name=logisticsCompanyName]").val($("#supervisionCompanyName").find("option:selected").text());
					});
					
					dialog.showDialog($("#recieveNotice_dialog"));
					
					$("#recieveNotice_dialog .dialogHandlerBtn").unbind("click").click(function(){
						databind.submitDom($("#recieveNotice_dialog .dialogContent"), function(){
							base.alert(1, "发起重新理货成功！");
							dialog.hideDialog($("#recieveNotice_dialog"));
							inquireWaitLoanNoticeBulkstockInventoryList();
						});
					});
				} else {
					base.alert(3, "请选择要重新理货的货箱！");
				}
			}
		});

		//点击确认收货
		$("#supervisionNotice").on("click", ".button-recieve", function() {
			if (checkeds.length <= 0) {
				layer.msg("请选择要确认收货的货箱！");
				return;
			}
			
			if ($.trim($("#supervisionNotice .inventoryDate").val()) == "") {
				layer.msg("请输入收货时间！");
				return;
			}
			
			layer.confirm('是否确认收货?', {
			  btn: ['确定','取消'] //按钮
			}, function(){
				
				$("#supervisionNotice .inventoryIds").html("");
				$("#supervisionNotice").attr("action", "receiveConfirmTallying");
				$("#supervisionNotice .inventoryDate").attr("name", "superviseTallyingCreateTime");
				$.each(checkeds, function() {
					var str = "<input name='inventoryId' value='" + this + "' type='hidden' />";
					$("#supervisionNotice .inventoryIds").append(str);
				});
				
				databind.submitDom($("#supervisionNotice"), function(){
					layer.msg("收货成功！");
					checkeds = [];
					router.route("main/supervisionNotice.html?financeId=" + financeId + "&left=" + left, true);
				});
			}, function(){
				
			});
		});
		
		//点击确认监管
		$("#supervisionNotice").on("click", "#loanSubmit", function() {
			if (checkeds.length <= 0) {
				layer.msg("请选择要监管的货箱！");
				return;
			}
			
			if ($.trim($("#supervisionNotice .inventoryDate").val()) == "") {
				layer.msg("请输入监管时间！");
				return;
			}
			
			layer.confirm('是否确认监管?', {
			  btn: ['确定','取消'] //按钮
			}, function(){
				$("#supervisionNotice").attr("action", "superviseTallying");
				$("#supervisionNotice .inventoryDate").attr("name", "superviseTallyingCreateTime");
				$.each(checkeds, function() {
					var str = "<input name='inventoryId' value='" + this + "' type='hidden' />";
					$("#supervisionNotice .inventoryIds").append(str);
				});
				
				databind.submitDom($("#supervisionNotice"), function(){
					layer.msg("监管成功！");
					checkeds = [];
					router.route("main/supervisionNotice.html?financeId=" + financeId + "&left=" + left, true);
				});
			}, function(){
				
			});
		});
	};
	
	var loadLogisticsCompanyPageList = function(bodyDomId, jsTpl) {
		base.fnAjax({
			action : "inquireLogisticsCompanyListByCompanyName.json",
			version : "v1.0",
			async : false,
			oData : {
				pageIndex : 1,
				pageSize : 1000
			}, // 传递参数
			fnSuccess : function(data) { // 成功回调
				if (data.status == 200) {
					var tpl = $("#" + jsTpl).html();
					var html = juicer(tpl, data);
					$("#" + bodyDomId).html(html);
					$("input[name=logisticsCompanyName]").val($("#supervisionCompanyName").find("option:selected").text());
				} else {
					base.alert(3, data.message);
				}
			}
		});
	}

	//获取理货任务  填充弹出框信息
	var inquireTallyingDetailUnusual = function(tallyingId) {
		base.fnAjax({
			action: "inquireTallyingDetail.json",
			oData: {
				tallyingId: tallyingId
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					databind.fillForm($(".unusualReportTask"), data.datas[0]);
					showImg($("#uploadFileSoundRecorde").parent().parent(), data.datas[0].soundRecorde);
					showImg($("#uploadFileAbnormalFile").parent().parent(), data.datas[0].abnormalFile);
				} else {
					base.alert(2, "信息获取失败");
				}
			}
		});
	}

	//显示图片
	var showImg = function(dom, fileUuids) {
		var fileUuids = fileUuids.split(",");
		var html = "";
		var imgSrc = "";
		for (var i = 0; i < fileUuids.length; i++) {
			imgSrc = fileUuids[i];
			if (imgSrc.length != 0) {
				html = '<a target="_Blank" href="/finance/api/1.0/downloadFile.file?fileUuid=' + imgSrc + '">';
				html += '<div class="finance-file" id="' + imgSrc + '">';
				html += '<img  src="../../../res/png/file_icon.png" class="finance-field-img"  alt="' + imgSrc + '" />';
				html += '<div class="fileName"></div></div></a>';

			}
		}
		$(dom).html(html);
	}

	//理货收货确认(平台)
	var receiveConfirmTallying = function() {
			base.fnAjax({
				action: "receiveConfirmTallying.json",
				oData: {
					inventoryId: checkeds
				},
				fnSuccess: function(data) {
					if (data.status == 200) {
						base.alert(1, "确认收货成功");
						checkeds = [];
						router.route("main/supervisionNotice.html?financeId=" + financeId + "&left=" + left, true);
					} else {
						base.alert(3, data.message);
					}
				}
			});
		}
		//理货收货监管确认(平台)
	var superviseTallying = function() {
		base.fnAjax({
			action: "superviseTallying.json",
			oData: {
				inventoryId: checkeds
			},
			fnSuccess: function(data) {
				if (data.status == 200) {
					base.alert(1, "确认监管成功");
					checkeds = [];
					router.route("main/supervisionNotice.html?financeId=" + financeId + "&left=" + left, true);
				} else {
					base.alert(3, data.message);
				}
			}
		});
	}
	
	var getRandomCode = function(callback) {
		base.fnAjax({
			action: "getRandomCode.json",
			oData: {
			},
			fnSuccess: function(data) {
				if (data.status == 200) {
					rd = data.datas[0].randomCode;
					callback();
				} else {
					base.alert(3, data.message);
				}
			}
		});
	}

	var passData = function(randomCode, data) {
		base.fnAjax({
			action: "passData.json",
			oData: {
				randomCode: randomCode,
				data: data
			},
			fnSuccess: function(data) {
				if (data.status == 200) {
					
				} else {
					base.alert(3, data.message);
				}
			}
		});
	}

	//理货详情
	var inquireTallyingDetail = function() {
		base.fnAjax({
			action: "inquireTallyingDetail.json",
			oData: {
				tallyingId: tallyingId
			},
			fnSuccess: function(data) {
				if (data.status == 200) {
					financeId = data.datas[0].financeId;
					tallyingId = data.datas[0].tallyingId;
					$("#tallyingNumber").html(data.datas[0].tallyingNumber);
					$("#finishedDateTime").html(data.datas[0].finishedDateTime);
					$("#clerkName").html(data.datas[0].clerkName);
					if (data.datas[0].tallyingState == 1) {
						$("#tallyingState").html("待理货");
					} else if (data.datas[0].tallyingState == 4) {
						$("#tallyingState").html("理货完成");
					} else if (data.datas[0].tallyingState == 5) {
						$("#tallyingState").html("已上报");
					}

					if (data.datas[0].abnormal == 0) { //异常
						$(".unusual").removeClass("none");
					}
					var tpl = $("#bulkstockTpl").html();
					var html = juicer(tpl, data);
					$("#bulkstockListBody").html(html);
				} else {
					base.alert(2, "信息获取失败");
				}
			}
		});
	}

	//查询理货任务列表
	var inquireWaitLoanNoticeBulkstockInventoryList = function() {
		base.fnAjax({
			action: "inquireBulkstockInventoryPageList.json",
			oData: {
				financeId: financeId,
				supervisionState: [1, 2],
				pageSize: 10000,
				pageIndex: pageIndex
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					juicer.register("inquireFile", tools.inquireFile);
					juicer.register("formatCurrency", tools.formatCurrency);
					
					if (productType == 3 || productType == 5 || productType == 6) {
						var tpl2 = $("#bulkstockTpl2").html();
						var html2 = juicer(tpl2, data);
						$(".notice_table2").html(html2);
						
						$("#supervisionNotice .repeatRecieve").html("打回");
					} else {
						var tpl = $("#bulkstockTpl").html();
						var html = juicer(tpl, data);
						$(".notice_table").html(html);
						
						var tpl1 = $("#bulkstockTpl1").html();
						var html1 = juicer(tpl1, data);
						$(".notice_table1").html(html1);
					}
					
					$.each($("table"), function() {
						var $this = $(this);
						if ($this.find("tr").length < 2) {
							$this.remove();
						}
					});
					
					$("#supervisionNotice .checkAll").unbind("click").click(function() {
						if ($("#supervisionNotice .checkAll").prop("checked")) {
							$("#supervisionNotice .supervisionNoticeCheckeds").prop("checked", true);
						} else {
							$("#supervisionNotice .supervisionNoticeCheckeds").prop("checked", false);
						}
						checkeds = [];
						$.each($("#supervisionNotice .supervisionNoticeCheckeds:checked"), function() {
							checkeds.push($(this).attr("inventoryId"));
						});
					});

					$("#supervisionNotice").on("click", ".supervisionNoticeCheckeds", function() {
						if($("#supervisionNotice .supervisionNoticeCheckeds:checked").length != $("#supervisionNotice .supervisionNoticeCheckeds").length){
							$("#supervisionNotice .checkAll").prop("checked", false);
						}else {
							$("#supervisionNotice .checkAll").prop("checked", true);
						}
						
						checkeds = [];
						$.each($("#supervisionNotice .supervisionNoticeCheckeds:checked"), function() {
							checkeds.push($(this).attr("inventoryId"));
						});
					});
					
//					$("#supervisionNotice").on("click", "tr", function() {
//						if ($(this).find(".supervisionNoticeCheckeds").prop("checked") == true) {
//							$(this).find(".supervisionNoticeCheckeds").prop("checked", false);
//						} else {
//							$(this).find(".supervisionNoticeCheckeds").prop("checked", true);
//						}
//						
//						if($("#supervisionNotice .supervisionNoticeCheckeds:checked").length != $("#supervisionNotice .supervisionNoticeCheckeds").length){
//							$("#supervisionNotice .checkAll").prop("checked", false);
//						}else {
//							$("#supervisionNotice .checkAll").prop("checked", true);
//						}
//						
//						checkeds = [];
//						$.each($("#supervisionNotice .supervisionNoticeCheckeds:checked"), function() {
//							checkeds.push($(this).attr("inventoryId"));
//						});
//					});
					
					setTimeout(function(){
						if (pageIndex < data.totalPageCount) {
							pageIndex ++;
							inquireWaitLoanNoticeBulkstockInventoryList();
						} else {
							for (var i = 0; i < $("#supervisionNotice .index").length; i++) {
								$($("#supervisionNotice .index")[i]).html(i+1);
							}
						}
					}, 10);
					
					$("#supervisionNotice .detail").unbind("click").click(function(){
						router.route("main/wareHouseDetail.html?caseNumber=" + $(this).parents("tr").attr("caseNumber") + "&financeNumber=" + $(this).parents("tr").attr("financeNumber"));
					});
				} else {
					base.alert(2, "信息获取失败");
				}
			}
		});
	}

	return {
		init: init
	};
});